import React from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Form, Modal, Button, message, Input } from 'antd';

const mapStateToProps = state => ({})
class ResourceEditModal extends React.PureComponent {

  constructor(props) {
    super(props);
    this.formRef = React.createRef();
    this.state = {
      buttonLoading: false,
    };
  }

  componentDidMount() {
  }

  handleFinish = (values) => {
    const { dispatch, formData: {sid}, flushData } = this.props;
    this.setLoading(true);
    dispatch({
      type: 'resource/postObjWithRes',
      payload: { url: '/resource/edit',
        sid,
        resourceCode: values.resourceCode,
        resourceName: values.resourceName
      },
      callback: (response)=>{
        if (response.statusCode === '0') {
          this.close();
          message.success('修改成功');
          flushData();
        } else {
          this.setLoading(false);
        }
      }
    });
  }
  ok = () => {
    this.formRef.current.submit();
  }

  setLoading = (flag) => {
    this.setState({
      buttonLoading: flag,
    });
  }

  close = () => {
    const { closeModal } = this.props;
    this.formRef.current.resetFields();
    closeModal();
    this.setState({buttonLoading: false});
  }

  render() {
    const { modalVisible, formData } = this.props;
    const { buttonLoading } = this.state;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>取消</Button>
        <Button size="small" loading={buttonLoading} onClick={this.ok} type="primary">保存</Button>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };

    return (
      <Modal
        footer={footer}
        title="编辑资源"
        visible={modalVisible}
        onCancel={this.close}
      >
        <Form
          ref={this.formRef}
          {...formItemLayout}
          style={{ marginTop: 12 }}
          onFinish={this.handleFinish}
          initialValues={formData}
        >
          <Form.Item
            name="resourceCode"
            label="资源Code"
            rules={[{ required: true, message: '请输入资源Code' }]}
          >
            <Input maxLength={50} placeholder="请输入资源Code"/>
          </Form.Item>
          <Form.Item
            name="resourceName"
            label="资源名称"
            rules={[{ required: true, message: '请输入资源名称' }]}
          >
            <Input maxLength={50} placeholder="请输入资源名称"/>
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(ResourceEditModal);
